package genCodeUtil.genRealize;


import genCodeUtil.genConfig.GenConfig;
import genCodeUtil.util.ValidateUtils;
import lombok.Data;
import freemarker.template.Configuration;

import java.io.File;
import java.io.FileWriter;
import java.util.Map;

/**
 * 代码生成器实现
 * By:Simon
 */
@Data
public class GenRealize extends BaseInit {

    //实体类名称
    private String modelName = "";
    //工程目录
    private String projectPath = GenConfig.PROJECT_PATH;
    //作者名称
    private String author = "";
    //表名
    private String tableName = "";


    public GenRealize(String modelName, String tableName, String author) {
        this.modelName = modelName;
        this.author = author;
        this.tableName = tableName;
    }

    /**
     * 功能描述:
     * 〈生成代码〉
     *
     * @Author: Simon
     * @Date: 2020/4/7 11:05
     */
    public void genCode(String templateName, Map<String, Object> data) {
        if (ValidateUtils.isNull(templateName, tableName, projectPath, modelName)) {
            new RuntimeException("参数不能为空");
        }
        //目标目录
        String targetPath = projectPath + getTargetByTemplateName(templateName);
        //文件名称
        String fileName = modelName + getSuffixByTemplateName(templateName);

        Configuration cfg = initFreemarkerConfiguration(projectPath + GenConfig.TEMPLATE_PATH);

        try {
            File file = new File(targetPath + "/" + fileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            cfg.getTemplate(templateName).process(data, new FileWriter(file));
            System.out.println(fileName + "生成成功");
        } catch (Exception e) {
            throw new RuntimeException(fileName + "生成失败!", e);
        }
    }

    /**
     * 功能描述:
     * 〈顺序生成〉
     *
     * @Author: Simon
     * @Date: 2020/4/7 11:51
     */
    public void genCodeQueue() {
        if (ValidateUtils.isNull(tableName, modelName)) {
            new RuntimeException("表名不能为空");
        }
        DataInit dataInit = new DataInit(config, author, modelName, tableName);
        GenModel genModel = new GenModel();
        //创建model,mapper,xml
        genModel.genCode(tableName, modelName);
        //创建Manager
        genCode(GenConfig.TEMPLATE_NAME_MANAGER, dataInit.getDataMapInitForManager());
        //创建Service
        genCode(GenConfig.TEMPLATE_NAME_SERVICE, dataInit.getDataMapInitForService());
        //创建ServiceImpl
        //genCode(GenConfig.TEMPLATE_NAME_SERVICE_IMPL, dataInit.getDataMapInitForServiceImpl());
        //创建Controller
        genCode(GenConfig.TEMPLATE_NAME_CONTROLLER, dataInit.getDataMapInitForController());
    }


}
